<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>图片自定义分割线切割工具（单输入框）</title>
  <!-- 引入 JSZip 和 FileSaver -->
  <script src="https://unpkg.com/jszip@3.10.1/dist/jszip.min.js"></script>
  <script src="https://unpkg.com/file-saver@2.0.5/dist/FileSaver.min.js"></script>
  <style>
    body {
      font-family: Arial, sans-serif;
      padding: 20px;
      background: #f4f4f4;
    }
    .container {
      max-width: 900px;
      margin: auto;
      background: white;
      padding: 30px;
      border-radius: 10px;
      box-shadow: 0 0 10px rgba(0,0,0,0.1);
    }
    h1 {
      text-align: center;
      color: #333;
    }
    .input-section {
      text-align: center;
      margin: 20px 0;
      font-size: 16px;
    }
    input[type="text"] {
      padding: 10px;
      font-size: 16px;
      width: 70%;
      margin: 10px 0;
    }
    button {
      padding: 10px 20px;
      font-size: 16px;
      margin: 10px;
      background: #007cba;
      color: white;
      border: none;
      border-radius: 5px;
      cursor: pointer;
    }
    button:hover {
      background: #005a87;
    }
    button:disabled {
      background: #ccc;
      cursor: not-allowed;
    }
    .upload {
      text-align: center;
      margin: 20px 0;
    }
    .preview {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
      margin-top: 20px;
      justify-content: center;
    }
    .piece {
      border: 1px solid #ddd;
      text-align: center;
      padding: 5px;
      width: 200px;
    }
    .piece img {
      max-width: 100%;
      height: auto;
      display: block;
    }
    .piece a {
      display: block;
      margin-top: 5px;
      font-size: 14px;
    }
    #downloadAll {
      display: block;
      margin: 20px auto;
    }
    .info {
      color: #555;
      font-size: 14px;
      margin: 10px 0;
    }
  </style>
</head>
<body>
  <div class="container">
    <h1>图片自定义分割线切割工具</h1>
    <p class="info">输入多条水平分割线的 Y 坐标（像素），用英文逗号隔开，如：1512,1900,3600</p>

    <!-- 单输入框，逗号分隔 -->
    <div class="input-section">
      <input 
        type="text" 
        id="linesInput" 
        placeholder="例如：1512,1900,3600（留空 = 不切割）" 
      />
      <p class="info">
        支持格式：<code>1512, 1900, 3600</code> 或 <code>1512,,1900,3600</code>（自动过滤空值和排序）
      </p>
    </div>

    <div class="upload">
      <input type="file" id="imageInput" accept="image/*" />
      <br /><br />
      <button onclick="document.getElementById('imageInput').click();">
        选择图片
      </button>
    </div>

    <button id="downloadAll" disabled onclick="downloadAllAsZip()">
      📦 一键下载全部为 ZIP
    </button>

    <div id="result" style="display:none;">
      <h3>分割结果（可单独下载）：</h3>
      <div id="pieces" class="preview"></div>
    </div>
  </div>

  <script>
    let imageDataUrls = {}; // 存储每张图片的 data URL

    // 解析用户输入的坐标字符串
    function parseCutLines(input) {
      const values = input
        .split(',')
        .map(s => s.trim())        // 去空格
        .filter(s => s !== '')     // 过滤空字符串
        .map(s => {
          const n = parseInt(s);
          return isNaN(n) || n < 0 ? null : n;
        })
        .filter(n => n !== null);  // 过滤非法数字

      if (values.length === 0) return [];

      // 排序 + 去重
      return [...new Set(values)].sort((a, b) => a - b);
    }

    // 主处理逻辑
    document.getElementById("imageInput").addEventListener("change", function (e) {
      const file = e.target.files[0];
      if (!file) return;

      const rawInput = document.getElementById("linesInput").value;
      const cutYs = parseCutLines(rawInput);

      const reader = new FileReader();
      reader.onload = function (ev) {
        const img = new Image();
        img.onload = function () {
          const width = img.width;
          const height = img.height;

          // 验证所有坐标是否合法（不能 >= 图片高度）
          for (let y of cutYs) {
            if (y >= height) {
              alert(`⚠️ 警告：分割线 Y=${y} 超过了图片高度 ${height}，已自动忽略。`);
              // 可选择过滤：cutYs = cutYs.filter(y => y < height);
            }
          }

          // 构建切割位置：[0, y1, y2, ..., height]
          let positions = [0, ...cutYs.filter(y => y < height), height];
          positions = [...new Set(positions)].sort((a, b) => a - b); // 再次确保有序无重

          if (positions.length < 2) {
            alert("无法切割：没有有效的分割位置。");
            return;
          }

          const canvas = document.createElement("canvas");
          const ctx = canvas.getContext("2d");

          const piecesContainer = document.getElementById("pieces");
          piecesContainer.innerHTML = "";
          imageDataUrls = {};

          // 开始切割每一段
          for (let i = 0; i < positions.length - 1; i++) {
            const top = positions[i];
            const bottom = positions[i + 1];
            const h = bottom - top;

            if (h <= 0) continue;

            canvas.width = width;
            canvas.height = h;
            ctx.clearRect(0, 0, width, h);
            ctx.drawImage(img, 0, -top, width, height);

            const dataUrl = canvas.toDataURL("image/jpeg", 0.95);
            const filename = `part_${i}.jpg`;
            imageDataUrls[filename] = dataUrl;

            const div = document.createElement("div");
            div.className = "piece";

            const imgEl = document.createElement("img");
            imgEl.src = dataUrl;
            imgEl.alt = `Part ${i}`;

            const downloadLink = document.createElement("a");
            downloadLink.href = dataUrl;
            downloadLink.download = filename;
            downloadLink.textContent = `第${i+1}段 (${top}–${bottom})`;

            div.appendChild(imgEl);
            div.appendChild(downloadLink);
            piecesContainer.appendChild(div);
          }

          document.getElementById("result").style.display = "block";
          document.getElementById("downloadAll").disabled = false;
        };
        img.src = ev.target.result;
      };
      reader.readAsDataURL(file);
    });

    // 批量打包下载为 ZIP
    function downloadAllAsZip() {
      const zip = new JSZip();
      for (const [filename, dataUrl] of Object.entries(imageDataUrls)) {
        const base64 = dataUrl.split(",")[1];
        zip.file(filename, base64, { base64: true });
      }
      zip.generateAsync({ type: "blob" }).then(function (content) {
        saveAs(content, "split_parts.zip");
      });
    }
  </script>
</body>
</html>